package eu.best.sercheng.frontier;

import java.net.URL;

import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedQueue;



public class Frontiere implements IFrontiere
{ 
	class UrlComparator implements Comparator<URL> {

		@Override
		public int compare(URL arg0, URL arg1) {
			int temp;
			try {
				temp = currentDomain.compareToIgnoreCase(arg1.getAuthority());
				currentDomain = arg1.getAuthority();
			
			}catch(Exception e){
				temp = 1;
			}
			return temp;
		}
		
	}
	
	private Set<String> cache;
	private Queue<URL> urlQueue;
	private int SIZE = 100000;
	private String currentDomain;
	
	public Frontiere(URL currentUrl) {
		this.currentDomain = currentUrl.getAuthority();
		cache = new TreeSet<String>();
		urlQueue = new PriorityQueue<URL>(SIZE, new UrlComparator());
	}
	
	@Override
	public synchronized URL getLink() {
		return urlQueue.poll();
	}

	@Override
	public synchronized void pushLink(List<URL> list) {
		for(URL url: list) {
			String urlString = url.toExternalForm();
			if(cache.contains(urlString) == true) {
				//Nothing happends - url was visited
			}
			else {
				if(url!=null){ urlQueue.add(url);
				cache.add(url.toExternalForm());
				}
			}
		}
	}
	
}
